<template>
  <span class="timer">
    {{ currentTime }}
  </span>
</template>
<script>
export default {
  data() {
    return {
      // 当前时间
      currentTime: this.parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}"),
      // 当前时间定时器
      currentTimer: null,
    };
  },
  mounted() {
    this.setCurrentTimer();
  },
  methods: {
    // 当前时间定时器
    setCurrentTimer() {
      if (this.currentTimer) {
        clearInterval(this.currentTimer);
      }
      this.currentTimer = setInterval(() => {
        this.currentTime = this.parseTime(
          new Date(),
          "{y}-{m}-{d} {h}:{i}:{s}"
        );
      }, 1000);
    },
  },
  beforeDestroy() {
    // 清除定时器
    if (this.currentTimer) {
      clearInterval(this.currentTimer);
    }
  },
  deactivated() {
    // 清除定时器
    if (this.currentTimer) {
      clearInterval(this.currentTimer);
    }
  },
};
</script>
<style lang="scss" scoped>
.timer {
  font-size: 18px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.9);
}
</style>
